from typing import List


class Solution:
    def isSelfCrossing(self, lst: List[int]) -> bool:
        # 记录最近的四条边的位置
        top_x, top_y = (0, 0), float("inf")
        right_x, right_y = float("inf"), (0, 0)
        bottom_x, bottom_y = (0, 0), float("-inf")
        left_x, left_y = float("-inf"), (0, 0)

        # 初始化当前位置
        x, y = 0, 0
        direction = 0  # 0=上，1=左，2=下，3=右

        for d in lst:
            if direction == 0:  # 向上
                if top_x[0] <= x <= top_x[1] and y <= top_y <= y + d:  # 和上一条向左的边相交
                    return True
                if x == right_x and y + d >= right_y[0]:  # 和上一条向上的边重合
                    return True
                right_x, right_y = x, (y, y + d)
                y += d
            elif direction == 1:  # 向左
                if left_y[0] <= y <= left_y[1] and x - d <= left_x <= x:  # 和上一条向下的边相交
                    return True
                if y == top_y and x - d <= top_x[1]:  # 和上一条向左的边重合
                    return True
                top_x, top_y = (x - d, x), y
                x -= d
            elif direction == 2:  # 向下
                if bottom_x[0] <= x <= bottom_x[1] and y - d <= bottom_y <= y:  # 和上一条向右的边相交
                    return True
                if x == left_x and x - d <= left_y[1]:  # 和上一条向下的边重合
                    return True
                left_x, left_y = x, (y - d, y)
                y -= d
            else:  # 向右
                if right_y[0] <= y <= right_y[1] and x <= right_x <= x + d:  # 和上一条向上的边相交
                    return True
                if y == bottom_y and x + d >= bottom_x[0]:  # 和上一条向右的边重合
                    return True
                bottom_x, bottom_y = (x, x + d), y
                x += d
            direction = (direction + 1) % 4
        else:
            return False


if __name__ == "__main__":
    print(Solution().isSelfCrossing([2, 1, 1, 2]))  # True
    print(Solution().isSelfCrossing([1, 2, 3, 4]))  # False
    print(Solution().isSelfCrossing([1, 1, 1, 1]))  # True
    print(Solution().isSelfCrossing([1, 1, 2, 1, 1]))  # True
    print(Solution().isSelfCrossing([1, 1, 2, 2, 1, 1]))  # True
